﻿using System;
using System.IO;
using System.Linq;

namespace GetSize
{
    class Storage
    {
        public static readonly string FILE = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data.data");
        public static void Set(int total, IOrderedEnumerable<Entry> list, Action<double> callback)
        {
            using (var stream = new StreamWriter(File.OpenWrite(FILE), System.Text.Encoding.Default, 1024))
            {
                var index = 0D;

                stream.AutoFlush = true;
                stream.WriteLine(total);

                foreach (var item in list)
                {
                    stream.WriteLine($"{item.FullName}*{(item.IsDirectory ? 1 : 0)}*{item.GetSize()}");
                    index++;
                    callback(index / total);
                }

                stream.Close();
            }
        }

        public static void Get(Action<double, Entry> callback)
        {
            using (var stream = new StreamReader(File.OpenRead(FILE)))
            {
                var total = int.Parse(stream.ReadLine());

                var index = 0D;

                while (!stream.EndOfStream)
                {
                    var line = stream.ReadLine();
                    if (line.Length == 0)
                    {
                        continue;
                    }
                    var temp = line.Split('*');
                    index++;
                    var entry = new Entry(temp[0])
                    {
                        IsDirectory = temp[1] == "1"
                    };
                    if (!entry.IsDirectory)
                    {
                        entry.FileSize = long.Parse(temp[2]);
                    }
                    callback(index / total, entry);
                }
                stream.Close();
            }
        }
    }
}
